import { reactive, watchEffect } from "vue"
import moment from "moment"

import jwtDecode from 'jwt-decode'

declare interface TokenReac {
    token: string;
    expire: string;
}


function useToken() {
    const _tokenReac = reactive<TokenReac>({
        token: "",
        expire: ""
    })

    //token 存入到内存localStorage当中
    watchEffect(() => {
        if (!_tokenReac.token) return
        const { exp } = jwtDecode(_tokenReac.token) as any
        _tokenReac.expire = exp
        if (_tokenReac.expire && _tokenReac.expire) {
            localStorage.setItem("token", JSON.stringify(_tokenReac))
        }
    })

    //设置Token
    function setToken(options: TokenReac) {
        _tokenReac.token = options.token
        _tokenReac.expire = options.expire
    }

    //同步localStorage 中的Token
    function _syncLocalToken() {
        const { token, expire } = JSON.parse(localStorage.getItem("token") || '{"token": "", "expire":""}')
        _tokenReac.token = token
        _tokenReac.expire = expire
    }

    //检测token有效期 true 表示已经过去
    function checkExpire() {
        _syncLocalToken()
        if (!_tokenReac.expire) return true
        if (moment().isAfter(moment(_tokenReac.expire + '000').subtract(1, 'hours'))) {
            console.log("token过期了...", { expire_time: moment(_tokenReac.expire + '000').format("YYYY-MM-DD HH:mm") })
            return true
        }
        return false
    }

    return {
        setToken,
        checkExpire,
        TOKEN: _tokenReac
    }
}


export default useToken